<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_fetchMenusPermission"
    :columns="columns"
    :row-selection="rowSelection"
    hidePagination
    :row-key="(record) => record.menuId"
  >
    <template #expandIcon="{ expanded, onExpand, record }">
      <DownOutlined
        v-if="record.children"
        :rotate="expanded ? 0 : -90"
        :style="{ float: 'left' }"
        @Click="
          (e) => {
            onExpand(record, e);
          }
        "
      />
    </template>
    <template #toolbars>
      <b-button icon="add" @click="() => onAdd(0)" code="system:menu:add"
        >新增</b-button
      >
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation' && !record.admin">
        <b-button
          icon="edit"
          type="link"
          @click="() => onEdit(record)"
          code="system:menu:edit"
          >编辑</b-button
        >
        <b-button
          icon="add"
          type="link"
          @click="() => onAdd(record.menuId)"
          code="system:menu:add"
          >新增</b-button
        >
        <b-button
          icon="del"
          type="link"
          @click="() => onDelete(record)"
          code="system:menu:remove"
          >删除</b-button
        >
      </template>
    </template>
  </ProTable>
  <FormModal :items="items">
    <template #icon="{ field, formState }">
      <IconSelect v-model:value="formState[field]" />
    </template>
  </FormModal>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { DownOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { handleTree, listToEnum, listToOption } from '@/utils/utils';
import {
  createMenu,
  deleteMenu,
  fetchMenuInfo,
  fetchMenusPermission,
  fetchSysNormalDisable,
  updateMenu,
} from '@/api/system';
import IconSelect from './components/Icons.vue';

const menus = ref<any>([]);

const tableRef = ref();
const formatResponse = (res: any) => {
  const rows = handleTree(res.data, 'menuId');
  menus.value = rows;
  return {
    rows,
    total: rows.length,
  };
};

const _fetchMenusPermission = async (params: any) => {
  const res = await fetchMenusPermission(params);
  const rows = handleTree(res.data, 'menuId');
  menus.value = rows;
  return {
    rows,
    total: rows.length,
  };
};
const sysNormalDisableOptions = ref<Global.Option[]>([]);
const sysNormalDisableEnum = ref<Record<string, any>>([]);
const init = () => {
  fetchSysNormalDisable().then((res) => {
    sysNormalDisableOptions.value = listToOption(
      res.data,
      'dictLabel',
      'dictValue',
    ) as Global.Option[];
    sysNormalDisableEnum.value = listToEnum(res.data, 'dictValue', 'dictLabel');
  });
};

init();

const rowSelection = ref<ProTableProps['rowSelection']>({
  onChange() {},
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '菜单名称',
    dataIndex: 'menuName',
    align: 'center',
    width: 200,
  },
  {
    title: '页面路径',
    dataIndex: 'path',
    hideInSearch: true,
    align: 'center',
    width: 200,
  },
  {
    title: '图标',
    dataIndex: 'icon',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '排序',
    dataIndex: 'orderNum',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '权限标识',
    dataIndex: 'perms',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: 80,
    valueEnum: {
      ...sysNormalDisableEnum.value,
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    width: 220,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '上级菜单',
    type: 'treeSelect',
    field: 'parentId',
    rules: [{ required: true, message: '请选择上级菜单', trigger: 'blur' }],
    props: {
      treeData: [
        {
          menuName: '主类目',
          menuId: 0,
          children: menus.value,
        },
      ],
      allowClean: true,
      fieldNames: { label: 'menuName', value: 'menuId' },
      placeholder: '请选择上级菜单',
    },
  },
  {
    label: '菜单类型',
    type: 'radio',
    field: 'menuType',
    props: {
      options: [
        { label: '菜单', value: 'M' },
        { label: '按钮', value: 'F' },
      ],
    },
  },
  {
    label: '菜单名称',
    type: 'input',
    field: 'menuName',
    rules: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    props: {
      placeholder: '请输入菜单名称',
    },
  },
  {
    label: '路由地址',
    type: 'input',
    field: 'path',
    rules: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
    hide: (state) => state.menuType === 'F',
    props: {
      placeholder: '请输入路由地址',
    },
  },
  {
    label: '图标',
    type: 'input',
    field: 'icon',
    props: {},
    hide: (state) => state.menuType === 'F',
  },
  {
    label: '显示排序',
    type: 'number',
    field: 'orderNum',
    rules: [
      { required: true, message: '请输入', trigger: 'blur', type: 'number' },
    ],
    props: {},
  },
  {
    label: '权限字符',
    type: 'input',
    field: 'perms',
    // rules: [{ required: true, message: '请输入权限字符', trigger: 'blur' }],
    props: {
      placeholder: '请输入权限字符',
    },
  },
  {
    label: '状态',
    type: 'radio',
    field: 'status',
    hide: (state) => state.menuType === 'F',
    props: {
      options: sysNormalDisableOptions.value,
    },
  },
]);

const { FormModal, open } = useFormModal({ size: 'small' });

const onAdd = async (parentId: number) => {
  open({
    title: '新增菜单',
    defaultValue: {
      parentId,
      menuType: 'M',
      status: sysNormalDisableOptions.value[0].value,
    },
    serviceApi: async (params: any): Promise<any> => {
      await createMenu(params);
      sleep(() => tableRef.value.refresh());
    },
  });
};

const onEdit = async (record: any) => {
  const { menuId } = record;
  const result = await fetchMenuInfo(menuId);
  open({
    title: '编辑菜单',
    defaultValue: {
      ...(result.data as Record<string, any>),
    },
    modalType: 'add',
    serviceApi: async (params: any): Promise<any> => {
      await updateMenu({
        ...params,
        menuId,
      });

      sleep(() => tableRef.value.refresh());
    },
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (record: any) => {
  const { menuId } = record;
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除该菜单吗？`,
    centered: true,
    onOk: async () => {
      await deleteMenu(menuId);
      sleep(() => tableRef.value.refresh());
      message.success('删除成功');
    },
  });
};
</script>
